<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------


Class PromoteAction extends NewzanAction
{
	public function getItemInfo()
	{
		$itemId = I('itemId');
		$msg = array(
				'code' => 'error',
				'msg' => '未知错误'
			);
		try {
			if(!$itemId)
				throw new Exception("参数错误", 1);

			$productMdel = M('products');
			$goods = $productMdel->where(array('num_iid'=> $itemId))->count('num_iid');
			if(!$goods)
				throw new Exception("商品信息不存在.", 1);
			unset($goods);
			$url = 'https://item.taobao.com/item.htm?id='. $itemId;
			$html = file_get_contents($url);
			unset($url);
			$method = preg_match('/rel="canonical"/', $html);
			if($method === 0)
				$method = 'src';
			else
				$method = 'data-src';
			$method = $method ? 'data-src' : 'src';

			preg_match_all('/src="(.*?)\_[0-9]{2}x/', $html, $matches);
		
			$itemPic = isset($matches[1]) ? $matches[1] : array();
			$item_imgs = array();
			foreach ($itemPic as $key => $value) {
				if($key == 0)
					continue;
				$item_imgs[] = $value;
			}
			$data = array(
					'num_iid' => $itemId,
					'item_imgs' => json_encode($item_imgs)
				);

			$productMdel->save($data);

			$msg['code'] = 'success';
			$msg['item_imgs'] = $item_imgs;
			unset($msg['msg']);
		} catch (Exception $e) {
			$msg['msg'] = $e->getMessage();
		}
		$this->display_json($msg);
	}
	
	/**
	 * 自动低价测款
	 */
	public function quick()
	{
		$this->loadJS('promote/auto_driver_selector','component/component.item.selector', 'promote/campaign_selector');
		//get the campaigns 
		$campaignMdl = new CampaignModel();
		$campaigns = $campaignMdl->getCampaigns($this->me['user_id']);
		$this->campaigns = $campaigns;
		
		//得到全部用户分类
		$productMdl = new ProductModel();
		$this->cats = $productMdl->getUserCats($this->me["user_id"]);
		
		//是否可以再新建推广计划 TODO 取决与当前用户的等级和目前已有的数量
		$this->cancreate = false;
		$this->display();
	}
	
	/**
	 * 全店低价引流
	 */
	public function attracted()
	{
		$this->loadJS('promote/campaign_selector', 'promote/attracted_driver_selector');
		
		//get the campaigns 
		$campaignMdl = new CampaignModel();
		$campaigns = $campaignMdl->getCampaigns($this->me['user_id']);
		$this->campaigns = $campaigns;

		$this->display();
	}

	/**
	 * 重点主打优化
	 */
	public function smart()
	{
		$step = (int) $this->_get('step');
		$step = $step ? $step : 1;
		if(IS_POST && ($step == 2 || $step == 3)) {
			switch ($step) {
				case 2:
					$num_ids = $this->_post('num_iid');
					$numCount = substr_count($num_ids, ',')+1;
					if(!$num_ids) 
						$this->error('请选择宝贝');
					$campaign_id = $this->_post('campaign_id');
					if(!$campaign_id)
						$this->error('请选择推广计划');

					$budget = $this->_post('budget');
					$limit = $this->_post('limit');
					$agreen = (int)$this->_post('agreen');
					$J_autoDrive = $this->_post('J_autoDrive');

					$budget = (float) str_replace( "￥" , "" ,$budget) ;
					$limit = (float) str_replace("￥" , "" , $limit);
					if($budget < 30.00 ){
						$this->error("推广计划的日预算不得小于30元");
					}

					if($limit < 0){
						$this->error("关键词不能小于0");
					} else if($limit > 0 && $limit < 0.05 ){
						$this->error("关键词的最高限价不得小于0.05元");
					}

					$productMdl = new ProductModel;
					$itemsInfo = $productMdl->getProductByIds($this->me['user_id'], $num_ids);
					if(count($itemsInfo) === $numCount && $numCount > 0) {
						$itemInfo = array();
						foreach ($itemsInfo as $num_id => $item) {
							$item['item_imgs'] = json_decode($item['item_imgs'], true);
							array_unshift($item['item_imgs'], $item['pic_url']);
							// unset($item['pic_url']);
							// $itemInfo['img_count'] = count($item['item_imgs']);

							$itemInfo[] = array(
									'num_iid' => $num_id,
									'title' => $item['title'], //mb_substr($item['title'], 0, 20, 'utf-8'),
									'item_imgs' => $item['item_imgs'],
									'img_count' => count($item['item_imgs'])
								);
						}

						$this->assign('itemInfo', json_encode($itemInfo));
						$this->assign('campaign_id', $campaign_id);
						$this->assign('product_id', $num_ids);
						$this->assign('budget', $budget);
						$this->assign('limit', $limit);

						$this->display('smartcreative');
					} else {
						$this->error("宝贝不存在");
					}
					break;
				case 3:
					$campaign_id = $this->_post('campaign_id');
					$product_id = $this->_post('product_id');
					$budget = $this->_post('budget');
					$limit = $this->_post('limit');
					$creative = $this->_post('creative');
					$J_autoDrive = $this->_post('J_autoDrive');
					if($J_autoDrive != "smart") {
						$this->error('系统出错！');
					}

					if( $budget < 30.00 ){
						$this->error("推广计划的日预算不得小于30元");
					}

					if($limit < 0 ){
						$this->error("关键词不能小于0");
					} else if($limit > 0 && $limit < 0.05 ){
						$this->error("关键词的最高限价不得小于0.05元");
					}

					$limit = $limit * 100;
					$camapaign_obj = D('Campaign');
					$campaign = $camapaign_obj->getCampaignById($this->me['user_id'], $campaign_id, false);
					if(empty($campaign)) {
						$this->error("选择的推广计划不存在，请尝试更新数据");
					}

					$params = array(
							'campaign_id' => $campaign_id,
							'limit' => floatval($limit),
							'budget' => floatval($budget),
							'drive_type' => 2,
							'flag' => 0
						);
					$tmp = array();
					$i = 0;
					foreach ($creative as $num_id => $j){
						$tmp[$i] = array(
								'product_id' => $num_id
							);
						foreach ($j as $key => $item) {
							$tmp[$i]['title'.$key] = $item['title'];
							$tmp[$i]['pic_url'.$key] = $item['img_url'];
						}
						$i++;
					}
					
					$params['items'] = $tmp;
					unset($tmp);
					require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
					$http = new Curl();
					$http->setOpt(CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
					$url = build_url("sinbadgateway/users/{$this->me['user_id']}/autoDrives");
					$res = $http->post($url, json_encode($params));
					if($http->httpStatusCode != 200) {
						$this->error('软件错误：'.$res->message);
					} else {
						self::setTitle($campaign['campaign']['title'], '云智投重点主打优化', $campaign_id, $this->me['user_id'], $campaign['campaign']['online_status']);
						$this->redirect('/promote/status?campaign_id='.$campaign_id);
					}
					break;
				default:
					redirect('/promote/wireless');
					break;
			}
		} else {
			$this->loadJS('template');
			//get the campaigns
			$campaignMdl = new CampaignModel();
			$campaigns = $campaignMdl->getCampaigns($this->me['user_id']);
			$this->campaigns = $campaigns;		
			//得到全部用户分类
			$productMdl = new ProductModel();
			$this->cats = $productMdl->getUserCats($this->me["user_id"]);
			
			$this->display();
		}
	}
    
	//自动选择宝贝，先按照销量来
	public function autoadd()
	{
		$productMdl = new ProductModel();
		$products = $productMdl->getUserProducts($this->me["user_id"], '' , '' , 1 ,  100, 'sales_count', 'desc',50023725);
		//@TODO filter一些不适合推广的类目，例如邮费类目等
		$this->display_json( $products );
	}
	
	public function quicksetup()
	{
		$campaign_id = (int) $_POST["campaign_id"];
		$need_confirm = 0;
		$drive_type = 4;
		$budget = $_POST['budget'];
		$limit = $_POST['limit'];
		$budget = (float) str_replace( "￥" , "" ,$budget) ;
		$limit = (float) str_replace("￥" , "" , $limit);
		$strategy = 'V2';

		$security = $_POST['J_autoDrive'];
		$action = getUrlAction($this->_server('HTTP_REFERER'));
		
		//if($action != $security)
		//	$this->error('服务出错');

		if( $budget < 30.00 ){
			$this->error("推广计划的日预算不得小于30元");
		}

		if($limit < 0 ){
			$this->error("关键词不能小于0");
		} else if($limit > 0 && $limit < 0.05 ){
			$this->error("关键词的最高限价不得小于0.05元");
		}
	
		// convert into int
		// $budget = $budget;
		$limit = $limit * 100;
		
		$camapaign_obj = D('Campaign');
		$campaign = $camapaign_obj->getCampaignById($this->me['user_id'], $campaign_id, false);
		if(empty($campaign)) {
			throw new NewzanException('选择的推广计划不存在，请尝试更新数据' , RetStatus::PARAM_ERR);
		}

		$products = array();
		if($security == 'quick') {
			$num_iids = $_POST['num_iid'];
			$num_iids = explode(',', $num_iids);
			if(!$num_iids) {
				$this->error("请选择宝贝");
			}
			$productsInfo = M('products')->field('title, num_iid, item_imgs, pic_url')->where(array('num_iid'=> array('IN', $num_iids)))->select(array('assoc_key'=>true));
			foreach($productsInfo as $itemId => $item){
				$len = ceil(mb_strlen($item['title'], 'utf-8')/2);
				$itemsImg = json_decode($item['item_imgs'], true);
				$products[] = array(
						'product_id' => $itemId,
						'title1' => mb_substr($item['title'], 0, 20, 'utf-8'),
						'pic_url1' => $item['pic_url'],
						'title2' => mb_substr($item['title'], $len, $len, 'utf-8'),
						// 'pic_url2' => (count($itemsImg) > 0) ? (strpos($itemsImg[0], 'http:') === true ? $itemsImg[0] : 'http:' . $itemsImg[0]) : $item['pic_url']
						'pic_url2' => (count($itemsImg) > 0) ? $itemsImg[0] : $item['pic_url']
					);
			}
		}

		require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
		$http = new Curl();
		$http->setOpt(CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
		$url = build_url("sinbadgateway/users/{$this->me['user_id']}/autoDrives");
		
		$params = array(
				'items' => $products,
				'campaign_id' => $campaign_id,
				'limit' => $limit,
				'budget' => $budget,
				'drive_type' => $drive_type
			);
		$res = $http->post($url, json_encode($params));
		if($http->httpStatusCode != 200) {
			$this->error($res->message);
		} else {
			self::setTitle($campaign['campaign']['title'], (($security == 'quick') ? '云智投低价引流' : '云智投全店低价引流'), $campaign_id, $this->me['user_id'], $campaign['campaign']['online_status']);
			$this->redirect('/promote/status?campaign_id='.$campaign_id.'?driver_type='.$security);
		}
	}
	
	public function smartsetup()
	{
		if($_POST['products']){
			$products = explode(',', $_POST['products'] );
		}else{
			$this->redirect('/promote/status');
		}
		$campaign_ids = $_POST['campaign_id'];
		$campaign_titles = $_POST['campaign_title'];
		$budgets = $_POST['budget'];
		$limits = $_POST['limit'];
		$need_confirms = $_POST['need_confirm'];
		$titles1 = $_POST['title1'];
		$titles2 = $_POST['title2'];
		$img_urls1 = $_POST['img_url1'];
		$img_urls2 = $_POST['img_url2'];
		$tags = $_POST['tags'];
		
		$syncMdl = new SyncModel;
		$syncMdl->syncProducts($this->me["user_id"], true,true);
		
		foreach( $products as $pid ){
			//first check the settings
			$campaign_id = $campaign_ids[$pid];
			$existent_products = D('ProductQueue')->getExistentProductIds($campaign_id);
			// 已经存在的直接跳过
			if(in_array($pid, $existent_products)){
				continue;
			}
			$campaign_title = $campaign_titles[$pid];
			$budget = $budgets[$pid];
			$limit = $limits[$pid];
			$strategy = DEFAULT_AUTO_ENGINE;
			$need_confirm = isset($need_confirms[$pid]) ? true : false;
			// check the budget and limit if they meet the basic requirement
			$budget = (float) str_replace( "￥" , "" ,$budget) ;
			$limit = (float) str_replace("￥" , "" , $limit);
			
			if( $budget < 30.00 ){
				throw new NewzanException( "推广计划的日预算不得小于30元"  , RetStatus::PARAM_ERR );
			}
			
			if($limit < 0 ){
				throw new NewzanException( "关键词限价不能小于0"  , RetStatus::PARAM_ERR );
			} else if($limit > 0 && $limit < 0.05 ){
				throw new NewzanException( "关键词的最高限价不得小于0.05元" , RetStatus::PARAM_ERR );
			}
			
			//update campaign or create a new campaign if nessasary
			//convert into int
			$budget = $budget;
			$limit = $limit * 100;
			
			$camapaign_obj = D("Campaign");
			// if no campaign selected then add a campaign
			if($campaign_id == 0){
				if( empty($title) ){
					//$this->error("新建推广计划至少需要一个标题");
					throw new NewzanException( "新建推广计划至少需要一个标题" , RetStatus::PARAM_ERR );
				}
			
				$data = array(
						'title' => $campaign_title,
						'budget' => $budget ,
						//'limit' => $limit,
				);
				$campaign_id = $camapaign_obj->addCamapaign($this->me["user_id"] , $campaign_title);
				// TODO 如果没有新建成功(比如超过4个推广计划), 报错!!!
			} else {
				// update the budget for the campaign
				$campaign = $camapaign_obj->getCampaignById($this->me['user_id'] , $campaign_id ,false);
				if( empty($campaign) ){
					throw new NewzanException('选择的推广计划不存在，请尝试更新数据' , RetStatus::PARAM_ERR);
				}elseif($campaign["budget"] != $budget){
					$result = $camapaign_obj->updateCampaignBudget( $this->me["user_id"] , $campaign_id , $budget);
				}
			}
			
			
			//开始添加自动推广产品
			
			
			$auto_pq_product = array(
					'product_id' => $pid,
					'user_id' => $this->me['user_id'],
					'strategy' => $strategy,
					'campaign_id' => $campaign_id,
					'adgroup_id' => 0,
					'default_price' => $limit,
					'max_expense' => 0,
					'type' => 1, //默认使用1
					'addtime' => time(),
					'updated' => time(),
					'title1' => $titles1[$pid],
					'title2' => $titles2[$pid],
					'img_url1' => $img_urls1[$pid],
					'img_url2' => $img_urls2[$pid],
					'mykeywords' => zh_strtolower($tags[$pid]),  // quick模式没有用户自定义关键词
					'need_confirm' => $need_confirm, // 一键推广模式产品比较多，不适宜进行确认
			);
			
			// TODO 不应该用replace, 在已经存在同product_id-campaign_id的情况下应该报错
			$succ = false;
			try {
				$succ = M("auto_pro_product_queue")->add($auto_pq_product , array());
			} catch (Exception $e) {
			}
			if($succ) {
				$added_pqs[] = array($pid, $campaign_id);
			}
		}
		
		//sumbit to carine server 
		// use Carine to asyncronizedly submit the queue
		$batch_size = 10;
		if($added_pqs) {
			$chunked_pqs = array_chunk($added_pqs, $batch_size);
			import("@.Library.Carine");
			foreach ($chunked_pqs as $chunk) {
				$carine = new Carine();
				$ret = $carine->startAutoProInit($chunk, false);
				if($ret !== true && $ret !== 'true' && $ret !== false && $ret !== 'false') { // 网络问题导致失败
					Log::record("product auto promote start error :  Return: $ret", Log::ERR);
					M("auto_pro_product_queue")
					->where(array( 'product_id' => $p['product_id'], 'campaign_id' => $campaign_id))
					->save(array('status'=>-1, 'msg'=>"网络错误"));
				}
			}
		}
		Log::save();
		cookie( $this->me['user_id'] . "_smarted_products" , null );
		$this->redirect('/promote/status');
	}

	public function manual()
    {
    	if($this->_get('refresh')==true){
        	$syncMdl = new SyncModel;
			$syncMdl->syncProducts($this->me["user_id"], true,true);
        }

		$user_id = $this->me["user_id"];
		$campaign_id = $this->_get('campaign_id');
        $this->campaign_id = $campaign_id;
		$campaignModel = new CampaignModel();
		$campaign = $campaignModel->getCampaignInfo($user_id, $campaign_id);
		$this->assign('campaign', $campaign);
        $this->loadJS('promote/manual_selector','component/component.item.selector');
        $productMdl = new ProductModel();
        $this->cats = $productMdl->getUserCats($this->me["user_id"]);
        $this->display();
    }
	public function manual_creative()
	{
		$id = I('id');
		$campaign_id = I('campaign_id');
		ParamsCheckUtils::checkNULL($id , '请选择宝贝');
		$productMdl = new ProductModel;
		$campaignMdl = new CampaignModel;
		$itemInfo = $productMdl->getProductById($id, '','num_iid,title,price,publish_time,pic_url,item_imgs');
		if(!$itemInfo)
			$this->error('请选择宝贝');

		$itemInfo['item_imgs'] = json_decode($itemInfo['item_imgs'], true);
		if(!$itemInfo['item_imgs'])
			$itemInfo['item_imgs'] = array();
		array_unshift($itemInfo['item_imgs'], $itemInfo['pic_url']);
		$itemInfo['img_count'] = count($itemInfo['item_imgs']);
		$this->item = $itemInfo;
		$this->assign('itemInfo', json_encode($itemInfo));

		$campaignInfo = $campaignMdl->getCampaignInfo($this->me['user_id'], $campaign_id);
		if(!$campaignInfo)
			$this->error('请选择推广计划');
		$this->assign('campaign', $campaignInfo);
		$this->assign('campaign_id', $campaign_id);
		$this->assign('product_id', $id);
		$this->assign('budget', $campaignInfo['budget']);
		$this->assign('limit', $campaignInfo['limit']);

		$this->loadJS("promote/creatives");
		$this->display();
	}
	public function manual_recommends()
	{
		$this->loadJS('component/component.keyword.selector', 'promote/manual_recommends');
		$this->adgroup_id = I('adgroup_id');
		$this->campaign_id = I('campaign_id');

		$user_id = $this->me["user_id"];
		$campaign_id = $this->_get('campaign_id');
		$campaignModel = new CampaignModel();
		$campaign = $campaignModel->getCampaignInfo($user_id, $campaign_id);
		$this->assign('campaign', $campaign);

		$this->display();
	}
	
	public function manualsetup()
	{
		$this->loadJS("custom.currency" , "jquery.sparkline" , "component/component.keyword.selector" , "custom.keywordmanager");
		//check if products have been selected or not
		$this->tabs = array("step1" => 1 , "step2" => 1 , "step3" => 0 );
	
		$product_id = $this->_get('product_id');
	
		// get area options
		import("@.Library.TaobaoAPI.taobaoAPI");
		$access_token = getUserAccessToken($this->me["user_id"]);
		$api = taobaoAPI::init($access_token);
		
		$syncMdl = new SyncModel;
		$syncMdl->syncProducts($this->me["user_id"], true);
		
		$proMdl = new ProductModel();
		$product = $proMdl->getProductById($product_id);
	
		//if no product found , then error it
		if(!$product) $this->error("该产品没找到,请尝试更新产品数据！");
	
		// get if this adgroup has already been created already
		$adgroup_obj = D("Adgroup");
		$adgroup = $adgroup_obj->hasAdgroup( $product["product_id"] );
		$this->mask = $adgroup ? 0 : 1;
		$this->adgroup_id = $adgroup ? $adgroup["adgroup_id"] : 0;
	
		$campaign_obj = D('Campaign');
		$campaigns = $campaign_obj->getCampaigns($this->me['user_id'] , false);
		if($adgroup){
			$campaigns[$adgroup["campaign_id"]]["selected"] = true;
	
			//only display one campaign
			$this->campaigns = array( $campaigns[$adgroup["campaign_id"]] );
			$this->keywords_limit = $adgroup["default_price"];
			$this->campaign_budget = $campaigns[$adgroup["campaign_id"]]["budget"];
		}else{
			$this->campaigns = $campaigns;
			$this->keywords_limit = 0;
			$this->campaign_budget = 0;
		}
	
		//$this->campaigns = $campaigns;
		$this->product = $product;
	
	
	
		// get area options
		import("@.Library.TaobaoAPI.taobaoAPI");
		$access_token = getUserAccessToken($this->me["user_id"]);
		$api = taobaoAPI::init($access_token);
		$provinces = $api->getAreaOptions(2);
		//$provinces_set = $api->getCampaignArea($campaign);
		$provinces_set = array();
		$provinces_final = array();
	
		foreach($provinces as $k=>$p){
			$provinces_final[$k] = $p;
			$provinces_final[$k]["selected"] = false;
			if( in_array($k , $provinces_set) ){
				$provinces_final[$k]["selected"] = true;
			}
	
	
			foreach($p["cities"] as $kk => $c){
				$selected = false;
	
				if( $provinces_final[$k]["selected"] ){
					$selected = true;
				}else{
					if( in_array($kk , $provinces_set) ){
						$selected = true;
					}
				}
				$provinces_final[$k]["cities"][$kk] = array( "name" => $c  , "selected" => $selected);
	
			}
	
		}
	
		$this->provinces = $provinces_final;
	
		$this->display();
	}
	
	//各种推广模式进行的情况查询
	public function status()
	{
		$this->is_create = $this->_get('t');
		$this->tabs = array("step1" => 1 , "step2" => 1 , "step3" => 1 );
		$user_id = $this->me['user_id'];

		$where_unfinished = array('user_id' => $user_id, '_string' => 'status<=1 OR need_confirm=1');
		$where_finished = array('user_id' => $user_id, 'status' => 2, 'need_confirm' => array('neq', 1), 'addtime' => array('egt', time() - 86400));

		$campaign_id = $this->_get('campaign_id');
		if($campaign_id) {
			$where_unfinished['campaign_id'] = $campaign_id;
			$where_finished['campaign_id'] = $campaign_id;
		}
		$sequence = $this->_get('sequence');
		if($sequence){
			$where_unfinished['sequence'] = $sequence;
			$where_finished['sequence'] = $sequence;
		}
		$unfinished_adgroups = M('auto_pro_product_queue')->where($where_unfinished)->order('addtime DESC')->select() ;
		$finished_adgroups = M('auto_pro_product_queue')->where($where_finished)->order('addtime DESC')->select() ;
		
		$campaignMdl = new CampaignModel();
		$campaigns = $campaignMdl->getCampaigns($this->me['user_id'] , false);
		if($unfinished_adgroups) {
			foreach($unfinished_adgroups as &$ad){
				$ad['campaign_title'] = isset($campaigns[ $ad['campaign_id']]) ?  $campaigns[ $ad['campaign_id'] ]['title'] : null;
			}
		}
		if($finished_adgroups){
			foreach($finished_adgroups as &$ad){
				$ad['campaign_title'] = isset($campaigns[ $ad['campaign_id']])?$campaigns[ $ad['campaign_id']]['title']:null;
			}
		}

		$this->unfinished_adgroups = $unfinished_adgroups;
		$this->finished_adgroups = $finished_adgroups;

		$driver_type = $this->_get('driver_type');
		if(!$driver_type){
			$driver_type = 'wireless';
		}
		$this->driver_type = $driver_type;

		$this->loadJS("promote/status");
		$this->display();		
	}
	
	/**
	 * 清空推广计划
	 * @return 
	 */
	public function clearschedule()
	{
		$campaign_id = $_POST['campaign_id'];
		$user_id = $this->me['user_id'];
		$params = array(
					'campaign_id' => $campaign_id,
					'page_size' => 200,
					'page_no' => 1
			        );
		import("@.Library.TaobaoAPI.taobaoAPI");
        $api = taobaoAPI::init();
		$res = $api->SimbaAdgroupsbycampaignidGetRequest($params);
		$tmp_adgroups = json_decode( json_encode( $res['adgroups']) , true);
		$online_adgrouops = isset($tmp_adgroups["adgroup_list"]["a_d_group"]) ? $tmp_adgroups["adgroup_list"]["a_d_group"] : array();
		//删除推荐计划下的推广组
		$adgroupMdl=new AdgroupModel();
		$del_adgroups=array();
		foreach($online_adgrouops as $ad){
			$adgroupMdl->removeAdroupByApi($ad['adgroup_id']);
			$del_adgroups[]=$ad['adgroup_id'];
		}
		//删除本地数据库中的推广组
		$whr = array(
		    			'campaign_id' => $campaign_id
		    		);
		$local_adgroups = $adgroupMdl->where($whr)->select( array('assoc_key' => true) );
		
		foreach($local_adgroups as $ad){
			$adgroupMdl->removeAdgroupFromDb($user_id, $ad['adgroup_id'], $campaign_id);
		}
		
		return $this->display_json( array('status'=>true, 'del_adgroups'=>$del_adgroups));		
	}

	public function autostatus()
	{
	    $this->is_create = $this->_get('t');
	    $this->tabs = array("step1" => 1 , "step2" => 1 , "step3" => 1 );
	    $user_id = $this->me['user_id'];
	    
		$unfinished_adgroups = M('auto_pro_product_queue')
				->where( array('user_id' => $user_id, '_string' => 'status<=1 OR need_confirm=1'))
				->order('addtime DESC')
				->select() ;
		$finished_adgroups = M('auto_pro_product_queue')
		// 'status' => array('in', array(-1, 2))
				->where( array('user_id' => $user_id, 'status' => 2, 'need_confirm' => array('neq', 1), 'addtime' => array('egt', time() - 86400)))
				->order('addtime DESC')
				->select() ;
		
		$campaignMdl = new CampaignModel();
		$campaigns = $campaignMdl->getCampaigns($this->me['user_id'] , false);
		if($unfinished_adgroups)
			foreach($unfinished_adgroups as &$ad)
	            $ad['campaign_title'] = isset( $campaigns[ $ad['campaign_id'] ] ) ?  $campaigns[ $ad['campaign_id'] ]['title'] : null;
		if($finished_adgroups)
			foreach($finished_adgroups as &$ad)
				$ad['campaign_title'] = $campaigns[ $ad['campaign_id'] ]['title'];
		
		$this->unfinished_adgroups = $unfinished_adgroups;
		$this->finished_adgroups = $finished_adgroups;
		$this->display();
	}

    public function switchoff()
    {
        $campaign_id = $this->_post('campaign_id');    
        $whr = array( 
            'campaign_id' => $campaign_id,
            'user_id' => $this->me['user_id']
        );
        $data = array( 'auto_type' => 0 );
        $mdl = M('campaigns');
        $res = $mdl->where( $whr )->save( $data);
        $data = array( 'drive_type' => 0 );
        $res = M('adgroups')->where( $whr )->save( $data ); 
        $this->display_json($res);
    } 

	public function wireless()
	{
		$this->loadJS('promote/campaign_selector','promote/wireless_selector', 'component/component.item.selector');
		//get the campaigns
		$campaignMdl = new CampaignModel();
		$campaigns = $campaignMdl->getCampaigns($this->me['user_id']);
		$this->campaigns = $campaigns;

		//得到全部用户分类
		$productMdl = new ProductModel();
		$this->cats = $productMdl->getUserCats($this->me["user_id"]);

		$this->display();
	}

	public function wireless_creative(){
		$this->assign('campaign_id', $this->_get('campaign_id'));
		$this->assign('num_iid', $this->_get('num_iid'));
		$this->assign('budget', $this->_get('budget'));
		$this->assign('limit', $this->_get('limit'));
		$this->loadJS("promote/creatives");
		$this->display();
	}

	public function item_info(){
		$num_id = $this->_get('num_iid');
		$productMdl = new ProductModel;
		$itemInfo = $productMdl->getProductById($num_id, '',
			'num_iid,title,price,publish_time,pic_url,item_imgs');
		$itemInfo['item_imgs'] = json_decode($itemInfo['item_imgs'], true);
		array_unshift($itemInfo['item_imgs'], $itemInfo['pic_url']);
		$itemInfo['img_count'] = count($itemInfo['item_imgs']);
		$this->display_json($itemInfo);
	}

	public function items_info(){
		$num_iids = $this->_get('num_iids');
		$num_iids = explode(',', $num_iids);
		$productsInfo = M('products')->field('title, num_iid, item_imgs, pic_url')->where(array('num_iid'=> array('IN', $num_iids)))->select(array('assoc_key'=>true));
		$products = array();
		foreach($productsInfo as $itemId => $item){
			$len = ceil(mb_strlen($item['title'], 'utf-8')/2);
			$itemsImg = json_decode($item['item_imgs'], true);
			$products[] = array(
				'product_id' => $itemId,
				'title1' => mb_substr($item['title'], 0, 20, 'utf-8'),
				'pic_url1' => $item['pic_url'],
				'title2' => mb_substr($item['title'], $len, $len, 'utf-8'),
				'pic_url2' => (count($itemsImg) > 0) ? $itemsImg[0] : $item['pic_url']
			);
		}
		$this->display_json($products);
	}

	private static function setTitle($campaignTitle, $checkTitle, $campaign_id, $user_id, $status)
	{
		if(strstr($campaignTitle, $checkTitle) === false) {
			$p = array(
					array(
							'title' => $checkTitle,
							'campaign_id' => $campaign_id,
							'user_id' => $user_id,
							'online_status' => $status
						)
				);
			R('Camapaign/setAutoDriveTitle', $p, 'Event');
		}
		return true;
	}

}